package com.beiji.lib.pen.ui.renderer

import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
import android.util.Log
import com.beiji.lib.pen.model.DotUnit
import com.beiji.lib.pen.model.PenStroke
import com.tqltech.tqlpencomm.bean.Dot

/**
 * Path渲染器
 * Created by X on 2018/6/21.
 */
class PathRenderer : Renderer() {

    private val path = Path()

    private var preX: Float = 0f
    private var preY: Float = 0f
    private var lastX: Float = -1f
    private var lastY: Float = -1f
    private var dotCountInOnePath: Int = 0
    private var maxForce = 600
    override fun reset() {
        preX = 0f
        preY = 0f
        lastX = -1f
        lastY = -1f
    }

    override fun draw(canvas: Canvas, stroke: PenStroke, dotMatrix: Matrix, paint: Paint?) {
        Log.i("PathRenderer", "draw stroke")
        val path = Path()
        for (i in stroke.list.indices) {
            val point = stroke.list[i]
            if (i == 0) {
                path.reset()
                path.moveTo(point.x.toFloat(), point.y.toFloat())
            } else {
                val lastPoint = stroke.list[i - 1]
                path.quadTo(lastPoint.x.toFloat(), lastPoint.y.toFloat(), (lastPoint.x + point.x) / 2f, (lastPoint.y + point.y) / 2f)
            }
        }
        //path.transform(dotMatrix)
        canvas.drawPath(path, paint!!)
    }

    override fun draw(canvas: Canvas, dot: DotUnit, paint: Paint?) {
        Log.i("PathRenderer", "draw dot")
        val curX = dot.x.toFloat()
        val curY = dot.y.toFloat()

        if (dot.type == Dot.DotType.PEN_DOWN || preX == 0f) {
            path.reset()
            path.moveTo(curX, curY)
        }
//        else if (dotCountInOnePath > 5) {
//            path.reset()
//            path.moveTo(lastX, lastY)
//            path.quadTo(preX, preY, (preX + curX) / 2, (preY + curY) / 2)
//            lastX = (preX + curX) / 2
//            lastY = (preY + curY) / 2
//            dotCountInOnePath = 0
//        }
        else {
            path.quadTo(preX, preY, (preX + curX) / 2, (preY + curY) / 2)
//            lastX = (preX + curX) / 2
//            lastY = (preY + curY) / 2
        }
//        dotCountInOnePath++

        preX = curX
        preY = curY
//        paint?.strokeWidth = (dot.force.toFloat() / maxForce) * 30
//        if (dot.type == Dot.DotType.PEN_UP) {
        canvas.drawPath(path, paint!!)
    }
}